package com.misyi.designpattern.chain;

/**
 * 责任链模式
 *
 * @author licong
 * @date 2021-09-22 下午7:46
 */
public class ChainPatternDemo {

    public static void main(String[] args) {
        // 执行 1, 2, 3
        Handler thirdHandler = new Handler3(null);
        Handler secondHandler = new Handler2(thirdHandler);
        Handler firstHandler = new Handler1(secondHandler);

        firstHandler.execute();

        // 执行 3, 1, 2
        thirdHandler = new Handler2(null);
        secondHandler = new Handler1(thirdHandler);
        firstHandler = new Handler3(secondHandler);

        firstHandler.execute();

        // 责任链的思想
        // 1. 将一个业务的多个步骤拆分开, 封装到不同的 handler 中去
        // 2. 支持业务流程基于 handler 动态组装, 形成不同的业务
        // 3. handler 作为业务组件, 可以进行复用

        // 好处
        // 1. 代码封装到 handler 中了, 如果业务逻辑发生变化, 只用修改一个 handler 即可
        // 2. 业务流程发生变化, 只需要调整 handler, 动态组装为新的业务流程.

    }


    // nn  + nn
    public static int fin(int n) {
        if (n <= 1) {
            return n + 1;
        }
        return fin(n - 1) + fin(n - 2);
    }


    public static abstract class Handler {

        protected Handler successor;

        public Handler(Handler successor) {
            this.successor = successor;
        }

        public abstract void execute();
    }


    public static class Handler1 extends Handler {

        public Handler1(Handler successor) {
            super(successor);
        }

        @Override
        public void execute() {
            System.out.println("执行功能1");
            if (successor != null) {
                successor.execute();
            }
        }
    }

    public static class Handler2 extends Handler {

        public Handler2(Handler successor) {
            super(successor);
        }

        @Override
        public void execute() {
            System.out.println("执行功能2");
            if (successor != null) {
                successor.execute();
            }
        }
    }

    public static class Handler3 extends Handler {

        public Handler3(Handler successor) {
            super(successor);
        }

        @Override
        public void execute() {
            System.out.println("执行功能3");
            if (successor != null) {
                successor.execute();
            }
        }
    }


}
